<?php


namespace app\cms\community\thirdPartyApi\aliyun\OSS;

use iflow\Utils\basicTools;

class OSSFileBase extends OSSBase
{

    public function getSignUrl(string $bucket, string $object, $timeOut = 3600, $method = 'GET', $options = null): string
    {
        return $this->ossClient -> signUrl(
            $bucket, $object, $timeOut, $method, $options
        );
    }

    /**
     * 删除文件
     * @param string $bucket
     * @param string $object
     * @return null
     */
    public function deleteObject(string $bucket, string $object)
    {
        return $this->ossClient -> deleteObject($bucket, $object);
    }

    /**
     * 获取 web直传文件地址
     * @param string $prefix
     * @param int $expire
     * @param array $callbackParam
     * @param array $condition
     * @return array
     */
    public function getOssWebUrl(string $prefix = '', int $expire = 3600, array $callbackParam = [], array $condition = [
        'content-length-range',
        0, 1048576000
    ]): array {
        $key = $this->config['access-key-secret'];
        $callback_string = json_encode($callbackParam);
        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $end = $now + $expire;
        $expiration = (new basicTools()) -> gmt_iso8601($end);

        $start = [
            'starts-with', '$key', $prefix
        ];
        $conditions[] = $condition;
        $conditions[] = $start;
        $arr = [
            'expiration' => $expiration,
            'conditions' => $conditions
        ];
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));
        return [
            'accessId' => $this->config['access-key-id'],
            'host' => $this->config['endpoint'],
            'policy' => $base64_policy,
            'signature' => $signature,
            'expire' => $end,
            'callback' => $base64_callback_body,
            'prefix' => $prefix
        ];
    }
}